package api

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"server/internal/app/model"
	"server/internal/app/serv"
	"server/internal/database"
	"server/internal/pkg/response"
	"server/pkg/jwts"
	"strings"
)

var LoginApi = new(loginApi)

// LoginApi 登录
type loginApi struct {
	model.User
}

// Login	登录
func (a loginApi) Login(c *gin.Context) {
	type Param struct {
		Username string `json:"username" binding:"required"`
		Password string `json:"password" binding:"required"`
	}
	var param Param
	if err := c.ShouldBindJSON(&param); err != nil {
		response.Success(c, "", err.Error())
		return
	}
	user := model.User{
		Username: param.Username,
		Password: param.Password,
	}
	user, ExpiresAt, err := serv.Login.Login(c, user)
	user.ExpiresAt = ExpiresAt
	if err != nil {
		response.Fail(c, "", err.Error())
		return
	} else {
		data := make(map[string]interface{})
		data["userinfo"] = user
		data["routePath"] = "/admin"
		response.Success(c, data, "登录成功")

	}

}

// RefreshToken 更新token
func (a loginApi) RefreshToken(c *gin.Context) {
	type Param struct {
		RefreshToken string `json:"refresh_token" binding:"required"`
	}
	var param Param
	if err := c.ShouldBindJSON(&param); err != nil {
		response.Success(c, "", err.Error())
		return
	}

	getToken := param.RefreshToken
	if getToken == "" {
		response.NotLogin(c, 101, "未登录")
		return
	}

	userInfo, err := jwts.Decrypt(getToken)
	if err != nil {
		response.NotLogin(c, 106, "登录超时")
		return
	}

	Db := database.DB
	var users model.User
	Db.Model(&users).Where("id = ?", userInfo.ID).First(&users)

	if users.ID == 0 {
		response.NotLogin(c, 101, "无效的登录")
		return
	}
	user, ExpiresAt, err := serv.Login.RefreshToken(c, users)
	user.ExpiresAt = ExpiresAt
	if err != nil {
		response.Fail(c, "", err.Error())
		return
	} else {
		data := make(map[string]interface{})
		data["userinfo"] = user
		data["routePath"] = "/admin"
		response.Success(c, data, "登录成功")

	}

}

// GetAvatar 获取头像
func (a loginApi) GetAvatar(c *gin.Context) {
	type Param struct {
		Username string `json:"username" binding:"required"`
	}
	var param Param
	if err := c.ShouldBindJSON(&param); err != nil {
		c.JSON(200, gin.H{"code": 1, "msg": "", "data": "1", "err": err.Error()})
		return
	}
	Db := database.DB
	Admin := model.User{}
	Db.Model(&Admin).Select("avatar").Where("username = ?", param.Username).First(&Admin)
	response.Success(c, Admin.Avatar, "")
}

// Logout 退出登录
func (a loginApi) Logout(c *gin.Context) {
	response.Success(c, "", "注销成功")
}

func (a loginApi) Index(c *gin.Context) {
	userInfo, _ := c.Get("userInfo")

	Db := database.DB
	type User struct {
		model.User
		Super bool `json:"super"`
	}

	_, user := serv.User.Read(userInfo.(model.User).ID)

	userToken := model.UserToken{}
	Db.Model(&userToken).Where("user_id=?", user.ID).First(&userToken)

	user.Token = userToken.Token
	user.RefreshToken = userToken.RefreshToken
	user.ExpiresAt = userToken.ExpiresAt

	data := make(map[string]interface{})
	data["user_info"] = user

	rules, _ := c.Get("rules")
	groupIds := strings.Split(rules.(string), ",")

	data["menus"] = serv.Menu.Tree(0, rules, groupIds)

	siteConfig := make(map[string]interface{})
	detail := model.Config{}
	Db.Model(&detail).Where("`group` =?", "basics").First(&detail)
	map2 := make(map[string]interface{})
	json.Unmarshal([]byte(detail.Value), &map2)
	siteConfig["siteName"] = map2["siteName"]
	siteConfig["logo"] = map2["logo"]
	siteConfig["record_number"] = map2["record_number"]
	siteConfig["version"] = map2["version"]
	siteConfig["upload"] = map[string]string{
		"maxsize":  "10485760",
		"mimetype": "jpg,png,bmp,jpeg,gif,webp,zip,rar,xls,xlsx,doc,docx,wav,mp4,mp3,pdf,txt",
		"mode":     "local",
		"savename": "/storage/{topic}/{year}{mon}{day}/{filesha1}{.suffix}",
	}
	data["siteConfig"] = siteConfig
	data["terminal"] = map[string]string{"install_service_port": "8000", "npm_package_manager": "yarn"}
	response.Success(c, data, "")
}
